/**
 * Created by kirno on 2017/4/14.
 */
/**
 * Created by Administrator on 2016/11/12.
 */
import $ from 'jquery';
import {message} from 'antd'
import {config} from './config';
import reqwest from "reqwest";
import Promise from 'bluebird';
import md5 from 'MD5';
import moment from 'moment';
import {car} from "./value";

const path = config.path;
const app = {
    serverUrl: config.serverUrl,
    imgServerUrl: config.imgServerUrl,
    fileUrl: config.fileUrl,
    loadIndex: "",
    pageLength: 20,

    setToken: function (token) { //存储Token值
        return localStorage.setItem("platFormtoken", token);  //localStorage没有时间限制的数据存储。添加键值对：localStorage.setItem(key,value)，将value存储到key字段
    },
    getToken: function () {  //获取token值
        return localStorage.getItem("platFormtoken"); //　获取键值：localStorage.getItem(key)
    },
    removeToken() {
        localStorage.removeItem("platFormtoken");
    },
    /**
     *   存储值
     */
    setData: function (key, value) {
        if (!value) {
            return;
        }
        if (typeof value == 'object') {
            localStorage.setItem(key, JSON.stringify(value));
        } else {
            localStorage.setItem(key, value);
        }
    },
    /**
     * 获取存储的值
     * @key 需要的值对应的Key
     * @defaultData 当返回的值是空的时候，返回
     */
    getData(key, defaultData) {
        try {
            var re = localStorage.getItem(key);
            if (re) {
                return JSON.parse(re);
            } else {
                return defaultData;
            }
        } catch (e) {
            return re;
        }
    },
    removeDate(key) {
        localStorage.removeItem(key);
    },
    post: function (url, data) {
        // 以下两个固定传给服务器的参数
        data.token = app.getToken();
        //data.log_type = '0';
        const re = app.ajax(url, data, "POST");
        return re;
    },
    postJson(url, data, succCallBack, errorCallBack) {
        data.token = this.getToken();
        this.ajaxJson(url, JSON.stringify(data), "POST", succCallBack, errorCallBack, "application/json; charset=utf8");
    },
    ajaxJson(url, data, method, succCallBack, errorCallBack) {
        this.ajax(url, data, method, succCallBack, errorCallBack, "application/json; charset=utf8");
    },
    put: function (url, data, succCallBack, errorCallBack) {
        app.ajax(url, data, "PUT", succCallBack, errorCallBack);
    },
    get: function (url, data) {
        let reqParam = "";
        if (data) {
            for (let key in data) {
                const item = data[key];
                if (!item) {
                    continue;
                }
                reqParam += key + "=" + item + "&"
            }
            reqParam += "token=" + app.getToken();
        }
        return app.ajax(url + "?" + reqParam, {}, "GET");
    },
    del: function (url, data) {
        var reqParam = "";
        for (var key in data) {
            reqParam += key + "=" + data[key] + "&"
        }
        reqParam.substr(0, reqParam.length - 1);
        return app.ajax(url + "?" + reqParam, {}, "DELETE");
    },
    ajax: function (url, data, method, contentType = 'application/x-www-form-urlencoded; charset=utf8',) {
        const reqUrl = config.serverUrl + url;
        app.log(reqUrl);
        return new Promise((resolve, reject) => {
            reqwest({
                url: reqUrl,
                data: data,
                method: method,
                dataType: "json",
                contentType: contentType,
            }).then((req) => {
                const {code, msg, data} = req;
                if (code === 1) {
                    app.log("请求：" + reqUrl + " 返回的数据：" + JSON.stringify(data));
                } else {
                    app.error("请求：" + reqUrl + " 返回的数据：" + JSON.stringify(msg));
                }
                switch (code) {
                    // 掉线的情况
                    case -1:
                        app.removeToken();
                        app.alert('请重新登录', 'error', 3);
                        window._this.props.history.push('/login');
                }
                resolve(req);
            }, ({Status, readyState}) => {
                if (config.debug) {
                    app.alert(`请求地址：${url} 请求参数：${JSON.stringify(data)} 请求状态： ${Status}，XMLHttpRequest对象的状态：${readyState}`, "error", 10);
                } else {
                    app.alert("网络错误，请检查网络", "error", 3);
                }
                reject({Status, readyState});
            });
        })
    },

    /**
     * 处理打印请求事件
     * @param url
     * @param data
     * @param method
     * @param contentType
     */
    ajaxPrinter: function (url, data, method, contentType = 'application/x-www-form-urlencoded; charset=utf8',) {
        app.log(url);
        return new Promise((resolve, reject) => {
            reqwest({
                url: url,
                data: data,
                method: method,
                dataType: "json",
                contentType: contentType,
            }).then((req) => {
                const {code, msg, data} = req;
                if (code === 1) {
                    app.log("请求：" + url + " 返回的数据：" + JSON.stringify(data));
                } else {
                    app.error("请求：" + url + " 返回的数据：" + JSON.stringify(msg));
                }
                switch (code) {
                    // 掉线的情况
                    case -1:
                        app.removeToken();
                        app.alert('请重新登录', 'error', 3);
                        window._this.props.history.push('/login');
                }
                resolve(req);
            }, ({Status, readyState}) => {
                if (config.debug) {
                    app.alert(`请求地址：${url} 请求参数：${JSON.stringify(data)} 请求状态： ${Status}，XMLHttpRequest对象的状态：${readyState}`, "error", 10);
                } else {
                    app.alert("网络错误，请检查网络", "error", 3);
                }
                reject({Status, readyState});
            });
        })
    },
    tokenInvalid(location) {
        app.alert("请重新登陆");
        location.push('/');
    },
    /**
     * 日期检测
     */
    testDate(value) {
        const reg = /([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))/;
        return reg.test(value);
    },
    log(msg) {
        if (config.debug) {
            console.log(msg);
        }
    },
    error(msg) {
        if (config.debug) {
            console.error(msg);
        }
    },
    /**
     * 弹出警告
     * @param msg 警告内容
     * @param times 时长 默认 1.5
     * @param type 警告类型可选值 success、error、warning、info 默认 info
     */
    alert(msg, type = "info", times = 1.5) {
        message.config({
            top: '35%',
            duration: 2,
        });
        message[type](msg, times);
    },


    /**
     * 对输入的内容进行去空格
     * @param str为输入的内容
     */
    trimSpace(str) {
        let result;
        result = str.replace(/(^\s+)|(\s+$)/g, "");
        result = result.replace(/\s/g, "");
        return result;
    },


    /**
     * 返回n位的随机数
     * @param n
     * @returns {*}
     */
    getRandom(n) {
        let ran = Math.random() * Math.pow(10, n);
        ran += '';
        return ran[0]
    },
    md5(value) {
        return md5(value);
    },
    timeFormat(value) {
        return moment(value).format("YYYY-MM-DD hh:mm:ss");
    },
    /**
     * 获取当前日期的n天前的日期
     */
    getBeforeDate(n) {
        let date = new Date();
        let year, month, day;
        date.setDate(date.getDate() - n);
        year = date.getFullYear();
        month = date.getMonth() + 1;
        day = date.getDate();
        let s = year + '-' + ( month < 10 ? ( '0' + month ) : month ) + '-' + ( day < 10 ? ( '0' + day ) : day);
        return s;
    },
    /**
     * 获取url后面的参数
     * @param data
     * @returns {string}
     */
    getParams:function (data) {
        let reqParam='';
        for (let key in data) {
            const item = data[key];
            if (!item) {
                continue;
            }
            reqParam += key + "=" + item + "&";
        }
        if(reqParam.length>0){
            reqParam=reqParam.substr(0,reqParam.length-1);
        }
        return reqParam;
    },
    /**
     * 判断值是否是正数
     * @param num
     */
    checkIsNum(num){
        let reg=/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
        return reg.test(num);
    },
    /**
     * 处理分钟转换成小时事件
     */
    handleMinuteToHour(value){
        if(value==null||value==undefined||value.length<=0){
            value=0;
        }
        let integer=value.toString().split('.')[0];
        let minuteAll=Number(integer);
        let hour=parseInt(minuteAll/60);
        let minute=minuteAll%60;
        let newStr='';
        if(hour>0){
            newStr=hour+"小时";
        }
        newStr+=minute+"分钟";
        return newStr;
    },
    /**
     * 处理打印事件
     */
    async handlePrintCar(id,ip){
        let result=await app.post(car.PRINT_CAROUTPUT,{car_id:id});
        if(result.code===1){
            let printData={
                printData:result.data.printData
            };
            let url='http://'+ip+':4000/printGather';
            let printResult=await app.ajaxPrinter(url,printData,'POST');
            if(printResult.code==1){
                app.alert(printResult.msg,'success',2);
            }else{
                app.alert(printResult.msg,'error',2);
            }
        }else{
            app.alert(result.msg,'error',2);
        }
    }
};

export default app;